<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="UTF-8">
		<title>收银</title>
		<link type="text/css" rel="stylesheet" href="/fontsawesome/css/font-awesome.css"/>
		<link type="text/css" rel="stylesheet" href="/css/style.css"/>
		<style>
			.vipInfo span{background-color: aliceblue;border-color: #b7b7b7;border-radius: 15%;
				padding-left:10px;padding-right:10px;padding-top:5px;padding-bottom:5px;text-align: center;font-size: 16px;line-height: 32px;}
            .fa-minus-square-o{padding-right: 15px;}
            .fa-plus-square-o{padding-left: 15px;}
		</style>
	</head>
	<body>
		<div class="main_box cashierOrder">
			<h2><span></span>收银</h2>
			<form action="#" method="post">
				<div class="search_box clearfix">
					<label class="f_left">添加商品：</label>
					<input type="search" placeholder="请输入商品编号" class="f_left search_input addShopping"/>
					<input type="button" value="确认" class="btn blue_btn"/>
				</div>
			</form>
			<form action="#" method="post">
				<div class="search_box clearfix">
					<label class="f_left">会员：</label>
					<input type="search" placeholder="请输入会员手机号" class="f_left search_input findVIP"/>
					<input type="button" value="查询" class="btn blue_btn"/>
					<span class="vipInfo"></span>
				</div>
			</form>
			<div class="cont_box">
				<!--购物车信息-->
				<!--订单商品-->
				<div class="user_top order_top"><i class="fa fa-cart-arrow-down" aria-hidden="true"></i> 购物车商品：</div>
				<table border="0" cellspacing="0" cellpadding="0" class="table">
					<thead>
					<tr>
						<!--<th>序号</th>-->
						<th>商品名称</th>
						<th style="width:100px">商品状态</th>
						<th>商品价格</th>
						<th>商品数量</th>
						<th>金额</th>
						<th>操作</th>
					</tr>
					</thead>
					<tbody id="tbl">
					<!-- 购物车内容-->
					</tbody>
					<tfoot>
					<tr>
						<td>合计：￥</td>
						<td class="account"></td>
					</tr>
					<tr style="display: none">
						<td>会员价：￥</td>
						<td class="accountVIP"></td>
					</tr>
					</tfoot>
				</table>

				<!--结算方式-->
				<div class="norder_box order_state">
					<h2><span></span>结算方式</h2>
					<ul class="pay_box clearfix">
						<li class="radio_box">
							<i class="fa fa-circle-thin fa-1x"></i>
							<input type="radio" name="payment" id="22"/>
							<span>现金</span>
						</li>
						<!--<li class="radio_box">-->
							<!--<i class="fa fa-circle-thin fa-1x"></i>-->
							<!--<input type="radio" name="payment" id="33"/>-->
							<!--<span>支付宝</span>-->
						<!--</li>-->
					</ul>
				</div>
				<div class="clearfix" style="margin-top:20px;">
					<input type="submit" value="结算" class="btn blue_btn total_btn">
				</div>
			</div>
		</div>
		<!--javascript include-->
		<script src="/js/jquery-2.2.1.min.js"></script>
		<script src="/js/jquery.dataTables.min.js"></script>
		<script src="/js/bootstrap-datepicker.js"></script>
		<script src="/js/jquery.validate.min.js"></script>
		<script src="/js/other.js"></script>

		<!-- 结算-->
		<script th:inline="javascript" type="text/javascript">
			$(function(){
				$.ajaxSetup({
					cache: false
				});
				//=====弹出窗设置
				function DelTipWidth(Twidth,Theight){
					$(".tip_box",Wparent).css({"width":Twidth+"px","height":Theight+"px","margin-top":-(Theight/2)+"px","margin-left":-(Twidth/2)+"px"});
					$(".tip_close",Wparent).on("click",Tipclose);
				}
				//=====关闭弹出窗
				function Tipclose(){
					$(".tip_box",Wparent).remove(); //移除新增的外层className
					$(".tip_bg",Wparent).remove(); //移除新增的背景className
				}
				//初始化
				var Wparent = window.parent.document,
					tipBg = "<div class='tip_bg'></div>",
					tipBox = "<div class='tip_box'></div>"
					goodsData = [],//商品数据
				//给支付方式设置一个默认选项
				// $("#22").prop("checked",true).prev().removeClass("fa-circle-thin").addClass("fa-check-circle");
				//最终结算
				$(".total_btn").click(function(){
					var tbss=document.getElementById("tbl");
					var rowes=tbss.rows;//rows.length获取表格的行数
					if(rowes.length <=0){
						$.layerTip("error","你还未添加商品，请先选择后再结算");
					}else{
						//循环判断购物车商品数量是否改变,修改数据库信息
						var tab=document.getElementById("tbl");
						var rows=tab.rows;//rows.length获取表格的行数
						for(var i=0;i<rows.length;i++){ //遍历表格的行
							//获取每条商品的数量
							var number = $(".cont_box table tbody tr:eq("+i+") .number").val();
							//获取每行商品id
							var productId = $(".cont_box table tbody tr:eq("+i+") .productId").text();
							var orderId =$(".cont_box table tbody tr:eq("+i+") .orderId").text();//获取订单id
							if(number != 1){
								//修改商品数据库信息
								$.ajax({
									type:"post",
									url:"/modifyShoppingCart",
									data:"number="+number+"&productId="+productId+"&orderId="+orderId,
									success:function(result){
										console.log("修改成功！")

									},
									error:function(error){
										console.log("修改失败！")
									}
								});
							}
						}
						//结算
						var totalMoney = $(".cont_box table tfoot .account").text();//获取总金额
						//判断是否是VIP
						var orderMoney ;
						if($(".cont_box table tfoot .accountVIP").parent().css("display") != "none"){
							//会员价
							orderMoney= $(".cont_box table tfoot .accountVIP").text();
						}else{
							//非会员
							orderMoney = -1;
						}
						var orderId =$(".cont_box table tbody tr:eq(0) .orderId").text();//获取订单id
						//判断是哪个结算方式
						var val = $('input[name="payment"]:checked').attr("id");
						if(val == 22){
							//现金
							$.ajax({
								type:"post",
								url:"/saveOrder",
								cache: false,
								async: false,
								data:"orderMoney="+orderMoney+"&orderId="+orderId+"&totalMoney="+totalMoney,
								success:function(result){
									if(result.state == true){
										// $.layerTip("success","现金结算成功，欢迎下次使用！ ");
										alert("现金结算成功，欢迎下次使用！ ");
									}else{
										// $.layerTip("error","结算失败，数据保存不成功！");
										alert("结算失败，数据保存不成功！ ");
									}
									window.location.href="/sales/cashierOrder";
								},
								error:function(error){
									$.layerTip("error","结算失败，扣款不成功！");
								},
							})
						}
						//else 	if(val == 33){
						// 	location="/alipay?"+"orderMoney="+orderMoney+"&orderId="+orderId+"&totalMoney="+totalMoney;
						// 	//支付宝
						// 	// $.ajax({
						// 	// 	type:"post",
						// 	// 	url:"/alipay",
						// 	// 	async: false,
						// 	// 	cache: false,
						// 	// 	data:"orderMoney="+orderMoney+"&orderId="+orderId,
						// 	// 	success:function(result){
						// 	// 		// $.layerTip("success","支付宝结算成功，欢迎使用 ");
						// 	// 		alert("支付宝结算成功，欢迎使用 ");
						// 	// 		$.post( "/saveOrder",
						// 	// 				"orderMoney="+orderMoney+"&orderId="+orderId+"&totalMoney="+totalMoney,
						// 	// 				function(data){
						// 	// 					console.log("保存成功！");
						// 	// 					window.location.href="/sales/cashierOrder";
						// 	// 				});
						// 	// 	},
						// 	// 	error:function(error){
						// 	// 		$.layerTip("error","结算失败，扣款不成功！");
						// 	// 	},
						// 	// });
						// }
						else{
							alert("没有找到结算方式");
						}

					}
				});
			});
		</script>
		<!-- 自动获取购物车总金额-->
		<script>
			function loadMoney(){
				var tab=document.getElementById("tbl");
				var rows=tab.rows;//rows.length获取表格的行数
				var account=0;//设置总金额
				var accountVIP=0;//设置总金额
				for(var i=0;i<rows.length;i++){ //遍历表格的行
					//获取要的数据，商品价格
					var price = $(".cont_box table tbody tr:eq("+i+") .price").text();
					var state = $(".cont_box table tbody tr:eq("+i+") .state").text();
					// alert(price);
					account = Number(account)+Number(price);
					if(state !=""){
						//商品为活动价商品
						accountVIP = Number(accountVIP)+Number(price);
					}else{
						//正常售价商品
						accountVIP = Number(accountVIP)+(Number(price)*0.98);
					}
				}
				$(".cont_box table tfoot .account").text(toDecimal(account));
				//计算VIP金额
				$(".cont_box table tfoot .accountVIP").text(toDecimal(accountVIP));
			};
		</script>
	</body>

	<!-- 查询商品并添加到购物车-->
	<script th:inline="javascript" type="text/javascript">
		$(".main_box .search_box :button[value='确认']").bind("click",function(){
			var id = $(".cashierOrder .addShopping").val();
			$.post(
					"/addShoppingCart",
					"productId="+id,
					function(data){
						if(data.shoppingCartInfo != null){
							//判断商品是否存在
							var tab=document.getElementById("tbl");
							var rows=tab.rows;//rows.length获取表格的行数
							var account=0;//设置总金额
							var flag = 0;//购物车中是否已存在此商品
							for(var i=0;i<rows.length;i++){ //遍历表格的行
								//获取要的商品ID数据
								var productId = $(".cont_box table tbody tr:eq("+i+") .productId").text();
								if(productId == data.shoppingCartInfo.productId){
									flag = 1;//存在
									var number = $(".cont_box table tbody tr:eq("+i+") .number").val();
									var unitPrice =  $(".cont_box table tbody tr:eq("+i+") .number").parent().prev().text();//获取单价
									$(".cont_box table tbody tr:eq("+i+") .number").parent().next().text(toDecimal(Number(unitPrice)*(Number(number)+1)));//设置金额
									$(".cont_box table tbody tr:eq("+i+") .number").val(Number(number)+1);//设置数量
									loadMoney();
									//删除数据库里添加的同一条购物车数据
									$.post(
											"/deleteShoppingCart",
											"id="+data.shoppingCartInfo.id,
											function(data){
												console.log(data.msg);
											}
									);
									return;
								}
							}
							if(flag != 1){
								// alert(data.shoppingCartInfo.number);
								//添加一行tr
								// alert(data.marketInfo.state);
								var state = data.marketInfo.state;
								var stateName;
								if(state === 1){
									stateName = "折";
								}else{
									stateName = "";
								}
								$(".cont_box table tbody").append(
										"<tr>" +
										"<td class='name'>"+data.name+"</td>" +
										"<td class='state' style='color:red'>"+stateName+"</td>" +
										"<td class='productId' style='display: none'>"+data.shoppingCartInfo.productId+"</td>" +
										"<td>"+toDecimal(data.shoppingCartInfo.unitPrice)+"</td>" +
										"<td>" +
											"<a href='javascript:void(0);' onclick='minusNumber(this)'><i class='fa fa-minus-square-o'></i></a>"+
											"<input style='width: 30px;display: inline-block' type='text' class='number' value='"+data.shoppingCartInfo.number+"'/>"+
											"<a href='javascript:void(0);' onclick='addNumber(this)'><i class='fa fa-plus-square-o'></i></a>" +
										"</td>" +
										"<td class='price'>"+toDecimal(data.shoppingCartInfo.price)+"</td>" +
										"<td class='orderId' style='display: none'>"+data.shoppingCartInfo.orderId+"</td>" +
										"<td>" +
											"<a href='javascript:void(0);' class='table_btn table_del del_btn'>" +
											"<i class='fa fa-trash-o'></i>" +
											"<span>删除</span>" +
											"</a>" +
										"</td>" +
										"<td class='id' style='display: none'>"+data.shoppingCartInfo.id+"</td>" +
										"</tr>"
								);
								loadMoney();
							}

						}else{
							alert("无此编号商品！");
						}
					}
			)
		})
	</script>
	<!-- 删除购物车商品-->
	<script type="text/javascript">
		$(".cont_box table tbody").delegate(".del_btn","click",function(){
			//获取删除的购物车订单id
			var id= $(this).parent().next().text();
			$.post(
					"/deleteShoppingCart",
					"id="+id,
					function(data){
						// alert(data.msg);
						console.log(data.msg);
					}
			);
			//移除删除的tr
			$(this).parent().parent().remove();
			loadMoney();//计算购物车总金额
		})
	</script>
	<!-- 查询会员号并显示会员名称-->
	<script th:inline="javascript" type="text/javascript">
		$(".main_box .search_box :button[value='查询']").bind("click",function(){
			var phone = $(".cashierOrder .findVIP").val();
			$.post(
					"/findVIP",
					"phone="+phone,
					function(data){
						if(data.consumerInfo != null){
							$(".main_box .search_box .vipInfo").html("<span>欢迎顾客："+data.consumerInfo.userName+"</span>");
							$(".cont_box table tfoot .accountVIP").parent().css("display","table-row");
						}else{
							alert("无此会员！");
							// $(".main_box .search_box .vipInfo").html("<input type='button' value='添加会员' class='btn blue_btn'/>");
						}
					}
			)
		})
	</script>
	<!-- 数量增减-->
	<script type="text/javascript">
		//增加
		function addNumber(exc){
			var number = $(exc).prev().val();
			var unitPrice = $(exc).parent().prev().text();
			// alert(number);
			// alert(unitPrice);
			$(exc).parent().next().text(toDecimal(Number(unitPrice)*(Number(number)+1)));
			$(exc).prev().val(Number(number)+1);
			loadMoney();
		};
		//减少
		function minusNumber(exc){
			var number = $(exc).next().val();
			var unitPrice = $(exc).parent().prev().text();
			if(Number(number) <= 1){
				$.layerTip("error","数量最少为1");
			}else{
				$(exc).parent().next().text(toDecimal(Number(unitPrice)*(Number(number)-1)));
				$(exc).next().val(Number(number)-1);
				loadMoney();
			}

		};
	</script>
	<!-- 刷新页面后删除未结算订单-->
	<script th:inline="javascript" type="text/javascript">
		$(function(){
			//获取订单id
			var orderId=[[${#session.getAttribute("orderId")}]];
			if(orderId != null && orderId != ""){
				//存在未结算订单，删除
				$.post(
						"/deleteShoppingCart",
						"orderId="+orderId,
						function(data){
							console.log(data.msg);
						}
				);
			}
		});
	</script>
	<!-- 强制保留2位小数，如：2，会在2后面补上00.即2.00-->
	<script>
		function toDecimal(number) {
			var float = parseFloat(number);
			if (isNaN(float)) {
				return false;
			}
			var float = Math.round(number*100)/100;
			var s = float.toString();
			var rs = s.indexOf('.');
			if (rs < 0) {
				rs = s.length;
				s += '.';
			}
			while (s.length <= rs + 2) {
				s += '0';
			}
			return s;
		}
	</script>

</html>